<?php


namespace app\api\controller;

use app\api\model\MemberModel;
use service\UtilService;
use think\facade\Cache;
use think\Request;

/**
 * @title   登录模块
 * @desc    登录模块
 * Class Login
 * @package app\api\controller
 */
class Login extends ApiController {

    /**
     * @title   方法2
     * @desc    类的方法2 哦
     * @author  gwind55
     * @version test
     * @method POST
     * @param int $page  0 999
     * @param int $limit 10
     *
     * @return int $id 0 索引
     */
    public function test()
    {

    }

    /**
     * @title 用户登录
     * @param string $account
     * @param string $password
     * @return string $token Token
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login() {
        $request = $this->request;
        list($account, $password) = UtilService::getMore(['account', 'password'], $request, true);

        if (!$account) $this->_loginFail('请输入登录账号');
        if (!$password) $this->_loginFail('请输入登录密码');
        if (!MemberModel::be(['account' => $account])) $this->_loginFail('登陆账号不存在!');

        $userInfo = MemberModel::where('account', $account)->find();

        if (!password_verify($password, $userInfo['pwd'])) {
            $this->_loginFail('账号或密码输入错误!');
        }

        if (!$userInfo['status']) $this->_loginFail('账号已被锁定,无法登陆!');

        $token = $this->uniqidReal();
        $time = time();
        $ip = get_client_ip();

        Cache::set(md5('meet_you' . $account), [$token, $time, $ip], 0);
        $hash_token = password_hash($token . $time . $account . $ip, PASSWORD_DEFAULT);

        $this->success('ok', [
            'token' => base64_encode(json_encode(['i' => $userInfo['id'], 't' => $hash_token]))
        ]);
    }

    /**
     * @title 获取Salt
     * @param string $account Account
     * @return string $salt Salt
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSalt(Request $request) {
        $account = input('account');

        if (empty($account)) {
            $this->_loginFail('请输入登录账号');
        }
        if (!MemberModel::be(['account' => $account])) $this->_loginFail('登陆账号不存在!');
        $userInfo = MemberModel::where('account', $account)->find();

        if (!$userInfo['status']) $this->_loginFail('账号已被锁定,无法登陆!');
        $salt = $userInfo['salt'];
        if (empty($salt)) {
            $salt = $this->_salt();
            $userInfo['pwd'] = password_hash(md5('123456' . $salt), PASSWORD_DEFAULT);
            $userInfo['salt'] = $salt;
            $userInfo->save();
        }
        $this->success('ok', [
            'salt' => $salt
        ]);
    }

    /**
     * @title 检查会员登录
     * @param token Token
     * @return token Token
     */
    public function check_login(Request $request) {
        $str = trim(input('token'));
        if ($this->_check_login($str)) {
            $this->success('ok', [
                'token' => $this->_token
            ]);
        } else {
            $this->_loginFail('您的账号已登出!');
        }
    }


    /**
     * @title 注册会员
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function register(Request $request) {
        list($account, $nickname, $password, $weixin, $phone, $icode, $code) = UtilService::getMore(['account', 'nickname', 'password', 'weixin', 'phone', 'icode', 'code'], $request, true);

        if (empty($account)) {
            $this->_loginFail('请输入联系人电话');
        }
        if (empty($weixin)) {
            $this->_loginFail('请输入微信号');
        }
        if (empty($phone)) {
            $this->_loginFail('请输入备用手机号');
        }
        if (empty($icode)) {
            $this->_loginFail('请输入推荐码');
        }
        if (empty($code)) {
            $this->_loginFail('请输入手机验证码');
        } elseif ($code != Cache::get(md5('meet_you_code' . $account))) {
            $this->_loginFail('无效的验证码！');
        }

        if (MemberModel::be(['account' => $account])) $this->_loginFail('账号已存在，不可重复注册!');
        if (empty($nickname)) {
            $this->_loginFail('请输入姓名');
        }
        $parent_id = intval($icode);
        $parent = MemberModel::where('id', $parent_id)->find();
        if (empty($parent)) $this->_loginFail('无效的推荐人!');
        $parent = $parent->toArray();

        if (!empty($parent['is_agent'])) $this->_loginFail('无效的推荐人，无法注册!');
        if (!$parent['status'])  $this->_loginFail('推荐人已被锁定,无法推荐!');

        $salt = $this->_salt();

        $data = [
            'account'   => $account,
            'nickname'  => $nickname,
            'create_at' => time(),
            'phone'     => $phone,
            'status'    => 1,
            'level'     => 0,
            'parent_id' => $parent_id,
            'icode'     => $account,
            'salt'      => $salt,
            'pwd'       => password_hash(md5($password . $salt), PASSWORD_DEFAULT)
        ];
        $member = new MemberModel($data);
        if ($member->save()) {
            $this->success('注册成功！');
        } else {
            $this->_loginFail('注册失败，请联系管理员!');
        }
    }

    /**
     * @title 获取手机验证码
     */
    public function getcode() {
        $request = $this->request->get();
        $account = $request['account'];
        if (empty($account)) {
            $this->_loginFail('请输入手机号码');
        }
        mt_srand(time()); // 播下随机数发生器种子
        $code = rand(10000, 99999);
        $content = '您的手机验证码为：' . $code;
        Cache::set(md5('meet_you_code' . $account), ['code'=>$code,'time'=>time()], 3600);
        $res = sendSms($account, $content);
        if ($res) {
            $this->success('验证码发送成功!');
        } else {
            $this->error('验证码发送失败！');
        }
    }

    /**
     * 生成唯一的uuid值
     * @param integer $lenght 生成的uuid长度
     */
    protected function uniqidReal($lenght = 13) {
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }


    public function get_enter_logo(){

    }
}